package com.pzh.logistics.controller;


import com.pzh.logistics.common.ResultVO;
import com.pzh.logistics.exception.GlobalException;
import com.pzh.logistics.exception.ResultEnum;
import com.pzh.logistics.mbg.model.User;
import com.pzh.logistics.pojo.form.UserRegisterForm;
import com.pzh.logistics.service.AddressService;
import com.pzh.logistics.service.UserInfoService;
import com.pzh.logistics.util.DozerUtil;
import com.pzh.logistics.util.ResultVOUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 用户注册
     * @param form
     * @param bindingResult
     * @return
     */
    @PostMapping("/register")
    public ResultVO register(@Valid @RequestBody UserRegisterForm form,
                                BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new GlobalException(ResultEnum.PARAM_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        User user = new User();
        DozerUtil.transfor(form, user);
        userInfoService.register(user);
        return ResultVOUtil.success();
    }

    /**
     * 用户修改个人信息
     * @return
     */
    @PostMapping("/edit")
    public ResultVO userEdit(@Valid @RequestBody UserRegisterForm form,
                                BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            throw new GlobalException(ResultEnum.PARAM_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        form.setUserId(user.getUserId());
        return ResultVOUtil.success(userInfoService.updateInfo(form));
    }

    /**
     * 用户查看个人信息
     * @return
     */
    @GetMapping("/detail")
    public ResultVO detail(){
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        return ResultVOUtil.success(userInfoService.findByUserId(user.getUserId()));
    }

}
